<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <FullScreen
        v-model="showDialog"
        :title="title"
        :btn-list="fullInfo.btnList"
        @returnBack="returnBack"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>项目信息</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-projectLeaderName>
                <el-input
                  v-model="formInfo.data.projectLeaderName"
                  type="input"
                  :disabled="true"
                  class="not-mongolia"
                  placeholder="请选择项目负责人"
                >
                  <template #append>
                    <el-icon @click="openProjectLeaderList"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-fillUserName>
                <el-input
                  v-model="formInfo.data.fillUserName"
                  type="input"
                  :disabled="true"
                  class="not-mongolia"
                  placeholder="请选择填报人"
                >
                  <template #append>
                    <el-icon @click="openFillUserList"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-projectFinanceLeaderName>
                <el-input
                  v-model="formInfo.data.projectFinanceLeaderName"
                  type="input"
                  :disabled="true"
                  class="not-mongolia"
                  placeholder="请选择项目财务负责人"
                >
                  <template #append>
                    <el-icon @click="openProjectFinanceLeaderList"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-deptName>
                <el-input
                  v-model="formInfo.data.deptName"
                  type="input"
                  :disabled="true"
                  :class="'not-mongolia'"
                  placeholder="请选择填报部门"
                >
                  <template #append>
                    <el-icon @click="openDeptList"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>
      </FullScreen>
    </div>
    <Select-users
      v-if="selectProjectLeaderInfo.visible"
      v-model:showDialog="selectProjectLeaderInfo.visible"
      :query="selectProjectLeaderInfo.query"
      :api="getRrgUserList"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectProjectLeaderCallBack"
    />
    <Select-users
      v-if="selectFillUserInfo.visible"
      v-model:showDialog="selectFillUserInfo.visible"
      :query="selectFillUserInfo.query"
      :api="getRrgUserList"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectFillUserCallBack"
    />
    <Select-users
      v-if="selectProjectFinanceLeaderInfo.visible"
      v-model:showDialog="selectProjectFinanceLeaderInfo.visible"
      :query="selectProjectFinanceLeaderInfo.query"
      :api="getRrgUserList"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectProjectFinanceLeaderCallBack"
    />
    <select-dept
      v-if="selectDeptInfo.visible"
      v-model:show-dialog="selectDeptInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="selectDeptInfo.query"
      :save-empty="true"
      @callback="selectDeptCallBack"
    />
  </div>
</template>

<script setup name="capitalProjectModify">
import {
  createCapitalProject,
  createCapitalProjectAndSave,
  getCapitalProjectById,
  updateCapitalProject,
} from '@/api/asset'
import { getRrgUserList } from '@/api/base.js'
import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index'
import FullScreen from '@/components/FullScreen/index'
import SelectUsers from '@/components/SelectUsers/index'
import SelectDept from '@/components/SelectDept/index'

const emit = defineEmits()
const { proxy } = getCurrentInstance()

const props = defineProps(['visible', 'title', 'id', 'type'])

let validatePlanStartTime = (rule, value, callback) => {
  //计划开始日期
  let planEndTime = formInfo.data.planEndTime
  if (value >= planEndTime && value && planEndTime) {
    callback(new Error('计划开始日期应小于计划结束日期！'))
  } else {
    callback()
  }
}
let validateRealityStartTime = (rule, value, callback) => {
  //实际开始日期
  let realityEndTime = formInfo.data.realityEndTime
  if (value >= realityEndTime && value && realityEndTime) {
    callback(new Error('实际开始日期应小于实际结束日期！'))
  } else {
    callback()
  }
}
let validatePlanEndTime = (rule, value, callback) => {
  //计划结束日期
  let planStartTime = formInfo.data.planStartTime
  if (value <= planStartTime && value && planStartTime) {
    callback(new Error('计划结束日期应大于计划开始日期！'))
  } else {
    callback()
  }
}
let validateRealityEndTime = (rule, value, callback) => {
  //实际结束日期
  let realityStartTime = formInfo.data.realityStartTime
  if (value <= realityStartTime && value && realityStartTime) {
    callback(new Error('实际结束日期应大于实际开始日期！'))
  } else {
    callback()
  }
}

const fullInfo = reactive({
  btnList: [
    { label: '保存并提交', event: saveAndSubmit, show: !props.id && proxy.$permission('capitalProject:saveAndSubmit') },
    { label: '保存', event: save, show: true }
  ],
})
// 表单相关
const formInfo = reactive({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '项目编号',
      value: 'code',
      type: 'input',
    },
    {
      label: '项目名称',
      value: 'name',
      type: 'input',
    },
    {
      label: '项目类型',
      value: 'assetCapitalSourceDictId',
      type: 'select-model',
      show: true,
      code: 'asset_project_type',
    },
    {
      label: '预算总额',
      value: 'amount',
      type: 'number',
      formatter: proxy.$fn.TripartiteMethodAsset,
      precision:
        proxy.$store.state.permission.systemConfig.assets_price_precision,
      max: 9999999999,
    },
    {
      label: '项目负责人',
      value: 'projectLeaderName',
      type: 'slot',
    },
    {
      label: '填报部门',
      value: 'deptName',
      type: 'slot',
    },
    {
      label: '填报人',
      value: 'fillUserName',
      type: 'slot',
    },
    {
      label: '项目财务负责人',
      value: 'projectFinanceLeaderName',
      type: 'slot',
    },
    {
      label: '填报日期',
      value: 'fillTime',
      type: 'date',
    },
    {
      label: '计划开始日期',
      value: 'planStartTime',
      type: 'date',
    },
    {
      label: '计划结束日期',
      value: 'planEndTime',
      type: 'date',
    },
    {
      label: '实际开始日期',
      value: 'realityStartTime',
      type: 'date',
    },
    {
      label: '实际结束日期',
      value: 'realityEndTime',
      type: 'date',
    },
    {
      label: '项目目的',
      value: 'goal',
      type: 'textarea',
      /* className: "not-br", */
      maxlength: 200,
    },
    {
      label: '项目背景',
      value: 'background',
      type: 'textarea',
      /* className: "not-br", */
      maxlength: 200,
    },
  ],
  rules: {
    code: [{ required: true, message: '请输入项目编号', trigger: 'blur' }],
    name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
    assetCapitalSourceDictId: [
      { required: true, message: '请输入项目类型', trigger: 'blur' },
    ],
    planStartTime: [
      {
        validator: validatePlanStartTime,
        trigger: 'change',
      },
    ],
    realityStartTime: [
      {
        validator: validateRealityStartTime,
        trigger: 'change',
      },
    ],
    planEndTime: [
      {
        validator: validatePlanEndTime,
        trigger: 'change',
      },
    ],
    realityEndTime: [
      {
        validator: validateRealityEndTime,
        trigger: 'change',
      },
    ],
  },
  labelWidth: '130px',
})
const selectProjectLeaderInfo = reactive({
  visible: false,
  saveEmpty: true,
  query: {
    hasAllDept: 1,
  },
})
const selectFillUserInfo = reactive({
  visible: false,
  saveEmpty: true,
  query: {
    hasAllDept: 1,
  },
})
const selectProjectFinanceLeaderInfo = reactive({
  visible: false,
  saveEmpty: true,
  query: {
    hasAllDept: 1,
  },
})
const selectDeptInfo = reactive({
  visible: false,
  query: {
    deptAuth: 'id',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

onMounted(() => {
  if (props.id) {
    getDetails()
  }
})

function openDeptList() {
  selectDeptInfo.visible = true
}
function selectDeptCallBack(row) {
  if (row) {
    formInfo.data['deptId'] = row.id
    formInfo.data['deptName'] = row.name
  } else {
    formInfo.data['deptId'] = ''
    formInfo.data['deptName'] = ''
  }
}
function openProjectLeaderList() {
  selectProjectLeaderInfo.visible = true
}
function selectProjectLeaderCallBack(row) {
  if (row) {
    formInfo.data['projectLeaderId'] = row.id
    formInfo.data['projectLeaderName'] = row.name
  } else {
    formInfo.data['projectLeaderId'] = ''
    formInfo.data['projectLeaderName'] = ''
  }
}
function openFillUserList() {
  selectFillUserInfo.visible = true
}
function selectFillUserCallBack(row) {
  if (row) {
    formInfo.data['fillUser'] = row.id
    formInfo.data['fillUserName'] = row.name
  } else {
    formInfo.data['fillUser'] = ''
    formInfo.data['fillUserName'] = ''
  }
}
function openProjectFinanceLeaderList() {
  selectProjectFinanceLeaderInfo.visible = true
}
function selectProjectFinanceLeaderCallBack(row) {
  if (row) {
    formInfo.data['projectFinanceLeaderId'] = row.id
    formInfo.data['projectFinanceLeaderName'] = row.name
  } else {
    formInfo.data['projectFinanceLeaderId'] = ''
    formInfo.data['projectFinanceLeaderName'] = ''
  }
}
function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  formInfo.ref.validate((valid) => {
    if (valid) {
      let api
      let params = formInfo.data
      const type = props.type
      if (type === 'create') {
        api = isSaveAndSubmit === true ? createCapitalProjectAndSave : createCapitalProject
      } else if (type === 'update') {
        api = updateCapitalProject
      }
      api(params).then((res) => {
        if (res && res.success) {
          showDialog.value = false
          emit('returnBack', true)
        }
      })
    } else {
      proxy.$message({
        message: '必填或非法校验未通过，请检查！',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
    }
  })
}
function returnBack() {
  showDialog.value = false
  emit('returnBack', true)
}
function getDetails() {
  getCapitalProjectById(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data
    }
  })
}
</script>

<style scoped lang="scss">
.flex {
  display: flex;
  flex: 1;
}
:deep(.patrol-table-wrap) {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.flex-select :deep(.el-input--small .el-input__inner) {
  height: 28px !important;
}
:deep(.el-form-item__content) {
  display: flex;
}
</style>
